package proxy

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

	"github.com/gin-gonic/gin"
)

func singleJoiningSlash(a, b string) string {
	aslash := strings.HasSuffix(a, "/")
	bslash := strings.HasPrefix(b, "/")
	switch {
	case aslash && bslash:
		return a + b[1:]
	case !aslash && !bslash:
		return a + "/" + b
	}
	return a + b
}

func NewSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {

	targetQuery := target.RawQuery
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		fmt.Println(req.Host)
		// this fixes the bug
		req.Host = ""
		// --
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery
		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
		}
	}
	return &httputil.ReverseProxy{Director: director}
}

type ReverseProxier struct {
	remote *url.URL
}

// @param endpoint:  http://www.hddznet.com
func NewReverseProxier(endpoint string) (*ReverseProxier, error) {

	remote, err := url.Parse(endpoint)

	if err != nil {
		return nil, err
	}

	return &ReverseProxier{
		remote: remote,
	}, err
}

func (this *ReverseProxier) Gin(ctx *gin.Context) {

	proxy := NewSingleHostReverseProxy(this.remote)
	proxy.ServeHTTP(ctx.Writer, ctx.Request)
}
